<?php
/**
 * @author jonathan <jo.link.noir@gmail.com>
 * @version 1.0: jo_link_noir
 * @date 07-01-2010
 */
class U1_Account_Validate extends SF_Form
{
	const NAME_CODE = 'code';


	/**
	 * Vérifie si le code d'activation est valide et retourne un objet stdClass
	 * @param string $code = null : Si null le code est chercher dans la variable $_GET
	 * @return SW_Player|null
	 */
	static public function createIfCodeValid($code = null)
	{
		if (null === $code && false === ($code = self::getCode()))
			return null;

		$id = substr($code, 32, strlen($code) - 45);
		return U1_DAO_User::create($id);
	}

	/**
	 * @return bool
	 */
	static public function issetCode()
	{
		return isset($_GET[self::NAME_CODE]);
	}

	/**
	 * Retourne le code récupérer dans la variable $_GET
	 * @return string|false
	 */
	static public function getCode()
	{
		return isset($_GET[self::NAME_CODE]) ? $_GET[self::NAME_CODE] : false;
	}

	static public function generateCode($id, $pseudo, $mail)
	{
		return md5('code-'.$pseudo.$mail).$id.uniqid();
	}


	/**
	* Crée un formulaire avec la méthode post.
	* @param string $action = self::DEFAULT_ACTION
	*/
	public function __construct($action = self::DEFAULT_ACTION)
	{
		parent::__construct('post', $action);
	}

	public function init()
	{
		$this->addElement(new SF_Form_Element_Text('mail'))
		->addElement(new SF_Form_Element_Password('password'));
	}

	/**
	* Retourne true si le formulaire à été valider.
	* @param array $values = null
	* @return bool
	*/
	public function isSubmit(array $values = null)
	{
		return $values ? isset($values['validate']) : isset($_POST['validate']);
	}

	/**
	 * @code
		U1_DAO_User::create(
			$this->elements['mail']->getUnfilteredValue(),
			$this->elements['password']->getUnfilteredValue(),
		);
	 * @endcode
	 * @return SW_Player|null
	 */
	public function create()
	{
		return U1_DAO_User::create(
			$this->elements['mail']->getUnfilteredValue(),
			$this->elements['password']->getUnfilteredValue()
		);
	}
}